package xyz.scootaloo.oj.offer

import org.junit.Test
import xyz.scootaloo.console.app.support.Tester

/**
 * @author flutterdash@qq.com
 * @since 2021/4/13 10:51
 */
class P58I {

    private fun reverseWords(s: String): String {
        val cache = StringBuilder()
        val res = StringBuilder()
        for (c in s) {
            if (c == ' ') {
                clearCache(cache, res)
            } else {
                cache.append(c)
            }
        }
        clearCache(cache, res)
        return res.trimEnd(' ').toString()
    }

    private fun clearCache(cache: StringBuilder, res: StringBuilder) {
        if (cache.isEmpty())
            return
        res.insert(0, ' ').insert(0, cache)
        cache.setLength(0)
    }

    @Test
    fun test0() {
        Tester.createTest(this::reverseWords)
            .addCase("the sky is blue", "blue is sky the")
            .addCase("  hello world!  ", "world! hello")
            .addCase("a good   example", "example good a")
            .testAndShow()
    }

}
